package com.mimi.practice

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.Intent
import androidx.activity.result.ActivityResultLauncher
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity

import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.IntentUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.Utils
import com.clj.fastble.BleManager

import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions

class PermissionControl(private val context: AppCompatActivity,
    launchers: Map<String, ActivityResultLauncher<Intent>?>) {

    private var settingsLauncher: ActivityResultLauncher<Intent>? = null
    private var cameraLauncher: ActivityResultLauncher<Intent>? = null
    private var bluetoothEnableLauncher: ActivityResultLauncher<Intent>? = null
    private var writeLauncher: ActivityResultLauncher<Intent>? = null

    private lateinit var bluetoothManager: BluetoothManager
    private lateinit var blueAdapter: BluetoothAdapter

    init { // 处理传入的 launchers
        settingsLauncher = launchers["settings"]
        cameraLauncher = launchers["camera"]
        bluetoothEnableLauncher = launchers["bluetooth"]
        writeLauncher = launchers["write"]
    }

    fun checkBluePermission(callback: (Boolean) -> Unit) {
        if (!XXPermissions.isGranted(context,
                Permission.BLUETOOTH_CONNECT,
                Permission.BLUETOOTH_SCAN,
                Permission.BLUETOOTH_ADVERTISE)) {
            XXPermissions.with(context).permission(Permission.BLUETOOTH_CONNECT)
                .permission(Permission.BLUETOOTH_SCAN).permission(Permission.BLUETOOTH_ADVERTISE)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        checkBlue(callback)
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) { //设置
                            LogUtils.dTag("checkBlue", GsonUtils.toJson(permissions))
                            val builder = AlertDialog.Builder(context)
                            builder.setCancelable(true)
                            builder.setTitle("扫描附近设备")
                            builder.setMessage("前往设置界面打开扫描附近设备权限")
                            builder.setPositiveButton("前往设置") { _, _ ->
                                val intent =
                                    IntentUtils.getLaunchAppDetailsSettingsIntent(Utils.getApp().packageName,
                                        false)
                                settingsLauncher?.launch(intent)
                            }
                            builder.show()
                        } else {
                            checkBluePermission(callback)
                        }
                        callback(false)
                    }
                })
        } else {
            checkBlue(callback)
        }
    }

    fun checkBlue(callback: (Boolean) -> Unit) {
        bluetoothManager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
        blueAdapter = bluetoothManager.adapter
        if (!blueAdapter.isEnabled || !BleManager.getInstance().isBlueEnable) { // 请求打开蓝牙
            val intent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
            bluetoothEnableLauncher?.launch(intent)
            callback.invoke(false)
        } else {
            callback.invoke(true)
        }
    }


    fun checkCamera(callback: (Boolean) -> Unit) {
        if (!XXPermissions.isGranted(context, Permission.CAMERA)) { //请求权限
            XXPermissions.with(context).permission(Permission.CAMERA)
                .request(object : OnPermissionCallback {
                    override fun onGranted(permissions: List<String>, all: Boolean) {
                        LogUtils.dTag("permissions", "onGranted")
                        callback.invoke(true)
                    }

                    override fun onDenied(permissions: List<String>, never: Boolean) {
                        if (never) {
                            val builder = AlertDialog.Builder(context)
                            builder.setCancelable(true)
                            builder.setTitle("相机")
                            builder.setMessage("使用添加设备功能需要允许相机权限，请前往设置界面允许相机权限")
                            builder.setPositiveButton("前往设置") { _, _ ->
                                val intent =
                                    IntentUtils.getLaunchAppDetailsSettingsIntent(Utils.getApp().packageName,
                                        false)
                                cameraLauncher!!.launch(intent)
                            }
                            builder.show()
                        } else {
                            checkCamera(callback)
                        }
                        callback.invoke(false)
                    }
                })
        } else {
            callback.invoke(true)
        }
    }

    fun checkWritePermission(callback: (Boolean) -> Unit) {
        if (!XXPermissions.isGranted(context, Permission.MANAGE_EXTERNAL_STORAGE)) {
            XXPermissions.with(context).permission(Permission.MANAGE_EXTERNAL_STORAGE)
                .request(object : OnPermissionCallback {
                    override fun onGranted(list: List<String>, b: Boolean) {
                        callback.invoke(true)
                    }

                    override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                        super.onDenied(permissions, doNotAskAgain)
                        if (doNotAskAgain) {
                            val builder = AlertDialog.Builder(context)
                            builder.setCancelable(true)
                            builder.setTitle("写入权限")
                            builder.setMessage("写入权限\n" + "\n" + "当导出Excel时，需要写入数据\n" + "\n" + "请前往设置界面打开写入权限")
                            builder.setPositiveButton("前往设置") { _, _ ->
                                val intent =
                                    IntentUtils.getLaunchAppDetailsSettingsIntent(Utils.getApp().packageName,
                                        false)
                                writeLauncher?.launch(intent)
                            }
                            builder.show()
                        } else {
                            checkWritePermission(callback)
                        }
                        callback.invoke(false)
                    }
                })
        } else {
            callback.invoke(true)
        }
    }
}